package mpay

import ws.MPayBankWSService
import ws.TransferCode
import ws.MPayBankWSServiceServiceSoapBindingStub
import ws.MPayBankWSServiceService

class PaymentService {

    static transactional = true

    MPayBankWSServiceServiceSoapBindingStub bankService
    MPayBankWSServiceService service


    def boolean checkAccountFromBank(String accountName) {
        bankService = (MPayBankWSServiceServiceSoapBindingStub)(service.MPayBankWSServicePort)
        return bankService.checkBankAccount(accountName)
    }

    def boolean checkBalanceFromBank(String accountName, Double amount) {
        bankService = (MPayBankWSServiceServiceSoapBindingStub)(service.MPayBankWSServicePort)
        return bankService.checkBalance(accountName, amount)
    }

    def TransferCode transferMoney(String fromAcc, String toAcc, Double amount) {
        bankService = (MPayBankWSServiceServiceSoapBindingStub)(service.MPayBankWSServicePort)
        return bankService.transferMoney(fromAcc, toAcc, amount)
    }

    def boolean authorizeAccount(String accountName, String pin) {
        bankService = (MPayBankWSServiceServiceSoapBindingStub)(service.MPayBankWSServicePort)
        return bankService.authorizeAccount(accountName, pin)
    }

    def boolean isMobile(String mobile) {
        // normal thai mobile phone number is 10 digits
        // 08x-xxx-xxxx or
        // 11 digits with area code
        // +66x-xxx-xxxx
        // check for the digits
        int digits = mobile.length();
        def pattern = ~ /\d+/

        // if mobile number is 11 digits, reformat to normal thai mobile phone
        // before process
        if (digits == 11) {
            // check for the format
            mobile = changeMobileFormat(mobile)
            digits = mobile.length()
        }  else if (digits != 11 && digits != 10) {
            println(mobile + " is correct number? false")
            return false
        }

        if (digits == 10) {
            // check if they contain all numbers
            println(mobile + " is correct number? " + pattern.matcher(mobile).matches())
            return pattern.matcher(mobile).matches()
        }

        println(mobile + " is correct number? false")
        return false
    }

    def String changeMobileFormat(String mobile) {
        // replace area code +66 with thai normal format 08XXXXXXXX
        if (mobile.contains("+66")) {
            mobile = mobile.replace("+66", "0")
        }

        println("return mobile number: " + mobile)
        return mobile

    }

    def String replaceSpaceWithPlus(String msg) {
        return msg.replace(' ', '+')
    }

    def boolean isExistMobile(String mobile) {
        def account = Account.findWhere(mobile: mobile)

        if (account != null) {
            return true
        }

        return false
    }
}
